package dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import pojo.PolicyType;

import common.RowMapper;
import common.SQLTemplate;

import dao.PolicyTypeDAO;

public class PolicyTypeDAOImpl extends BaseDAO implements PolicyTypeDAO {

	@Override
	public List<PolicyType> getPolicyTypes() {
		String sql = SQLTemplate.POLICY_TYPE_SELECT_TEMPLATE + ";";
		List<PolicyType> policyTypes = null;
		try {
			policyTypes = (List<PolicyType>) queryForList(sql,
					new PolicyTypeRowMapper());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return policyTypes;
	}

	@Override
	public PolicyType add(PolicyType policyType) {
		String tableName = "T_POLICY_TYPE";
		String[] columnNames = { "TYPE" };
		String[] values = { policyType.getType() };
		String sql = SQLTemplate.addSQLTemplate(tableName, columnNames, values);
		try {
			insert(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return policyType;
	}

	@Override
	public PolicyType update(PolicyType policyType) {
		String tableName = "T_POLICY_TYPE";
		String[] columnNames = { "TYPE" };
		String[] values = { policyType.getType() };
		String sql = SQLTemplate.updateSQLTemplate(tableName, columnNames,
				values) + "WHERE ID='" + policyType.getId() + "';";
		try {
			update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return policyType;
	}

	@Override
	public boolean deleteById(String id) {
		boolean state = false;
		String sql = SQLTemplate.deleteSQLTemplate("T_POLICY_TYPE")
				+ "WHERE ID='" + id + "';";
		try {
			delete(sql);
			state = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return state;
	}
	private class PolicyTypeRowMapper implements RowMapper<Object> {
		private PolicyTypeRowMapper() {
		}

		public PolicyType mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			String id = rs.getString("id");
			String type = rs.getString("type");
			PolicyType policyType = new PolicyType();
			if (id != null) {
				policyType.setId(id);
			}
			if (type != null) {
				policyType.setType(type);
			}
			return policyType;
		}
	}
}
